package com.xg.serviceOrder.controller;


import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.xg.serviceOrder.entity.Alipay;
import com.xg.serviceOrder.service.UsedCarOrderItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class AlipayController {

    @Autowired
    private UsedCarOrderItemService usedCarOrderItemService;


    @GetMapping("/pay")  // &subject=xxx&traceNo=xxx&totalAmount=xxx参数结构
    public String pay(Alipay aliPay) {
        AlipayTradePagePayResponse response;
        try {
            //  发起API调用（以创建当面付收款二维码为例）
            response = Factory.Payment.Page()
                    .pay(URLEncoder.encode(aliPay.getSubject(), "UTF-8"), aliPay.getTraceNo(), aliPay.getTotalAmount(), "http://localhost:9002/usedCar/queryUsedCarListHome");
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return response.getBody();
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            //商户订单号
            String tradeNo = params.get("out_trade_no");
            //买家付款时间
            String gmtPayment = params.get("gmt_payment");
            //支付宝交易凭证号
            String alipayTradeNo = params.get("trade_no");
            //买家付款金额
            double pay_price= Double.parseDouble(params.get("buyer_pay_amount"));
            // 支付成功后，修改自己的订单状态、
            Map<String,Object> map = new HashMap<>();
            map.put("tradeNo",tradeNo);
            map.put("gmtPayment",gmtPayment);
            map.put("alipayTradeNo",alipayTradeNo);
            map.put("pay_price",pay_price);
            usedCarOrderItemService.updateOrderAndUsedCar(map);
        }
        return "success";
    }
}
